package com.shadowlight.hero_story;

import com.google.protobuf.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class GameMsgDecoder extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof BinaryWebSocketFrame)) {
            return;
        }

        BinaryWebSocketFrame f = (BinaryWebSocketFrame) msg;
        ByteBuf byteBuf = f.content();

        byteBuf.readShort();    //读取消息的长度
        int msgCode = byteBuf.readShort();  //读取消息的编号

        Message.Builder builder = GameMsgRecognizer.getMessageBuilderByMsgCode(msgCode);
        if (builder == null) {
            log.error("msgCode:{} 对应的messageBuilder不存在", msgCode);
            return;
        }

        //拿到消息体
        byte[] msgBody = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(msgBody);

        builder.clear();
        Message message = builder.mergeFrom(msgBody).build();

        if (null != message) {
            ctx.fireChannelRead(message);
        }
    }
}
